package concurrentDemo

import (
	"fmt"
	"time"
)

func StartDemo() {
	//m1()
	//m2()
	m3()
}

func m3() {
	//message := make(chan string)    //无缓冲
	message := make(chan string, 2) //有缓冲
	count := 3
	go func() {
		for i := 0; i < count; i++ {
			fmt.Println("befor send message", i)
			message <- fmt.Sprintf("message %d", i)
			fmt.Println("after send message", i)
		}
	}()
	fmt.Println("befor sleep")
	time.Sleep(3 * time.Second)
	fmt.Println("after sleep")
	for i := 0; i < count; i++ {
		fmt.Println(<-message)
	}
}

func m2() {
	ci := make(chan int)
	go func() {
		fmt.Println("gorouine message 0")
		ci <- 1 //写入时会锁住执行进程，等待读取器准备好后才写入
		time.Sleep(3 * time.Second)
		fmt.Println("gorouine message 2") //可能不会输出
	}()
	fmt.Println("main message")
	<-ci //未缓冲channel，同步，锁死直到设置完成值
}

func m1() {
	go func() {
		fmt.Println("Hello")
	}()
	fmt.Println("World") //当前goroutines执行
	time.Sleep(5 * time.Second)
}
